package com.ukao.pad.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.AddClothingAdapter;
import com.ukao.pad.adapter.RemoveClothingAdapter;
import com.ukao.pad.base.BaseDialogFragment;
import com.ukao.pad.bean.AddClothingItem;
import com.ukao.pad.bean.StringBean;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.listener.OnClothingListener;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.CustomPopWindow;
import com.ukao.pad.widget.StateImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class EditClotingDialogFragment extends BaseDialogFragment {


    @BindView(R.id.fragment_header_choose_recycler)
    RecyclerView hRecycler;
    @BindView(R.id.add_edit)
    ClearEditText addEdit;
    @BindView(R.id.add_btn)
    StateImageView addBtn;
    @BindView(R.id.search_edit)
    ClearEditText searchEdit;
    @BindView(R.id.search_btn)
    StateImageView searchBtn;
    @BindView(R.id.search_layout)
    RelativeLayout searchLayout;
    @BindView(R.id.add_search_layout)
    LinearLayout addSearchLayout;
    @BindView(R.id.fragment_addclothing_project_recycler)
    RecyclerView mRecycler;
    @BindView(R.id.tv_title)
    TextView title;
    private Unbinder unbinder;
    private List<AddClothingItem> list;
    private AddClothingAdapter mAdapter;
    private ArrayList<AddClothingItem> hlist;
    private ArrayList<AddClothingItem> mSearchlist;
    private AddClothingAdapter mStockinAdapter;
    private RemoveClothingAdapter hAdapter;
    private boolean isSingle;
    private List<AddClothingItem> strings = new ArrayList<>();
    private RecyclerView searchrecyclerView;
    private CustomPopWindow mSearchPopWindow;
    private int typeEnter;
    private ArrayList<StringBean> mDesclist;
    private JSONArray mJSONArray;
    private ArrayList<StringBean> mSelectDesclist;
    private OnClothingListener mOnClothingListener;
    private StringBuffer mStringBuffer;
    private String titles;

    public void setOnClothingListener(OnClothingListener mOnClothingListener) {
        this.mOnClothingListener = mOnClothingListener;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        list = getArguments().getParcelableArrayList(ARG_PARAM1);
        hlist = new ArrayList<>();
        typeEnter = getArguments().getInt(ARG_PARAM2);
        mDesclist = getArguments().getParcelableArrayList(ARG_PARAM3);
        isSingle = getArguments().getBoolean(ARG_PARAM4);
        titles = getArguments().getString(ARG_PARAM5);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_addclothing_project, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();

        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        title.setText(titles);
        defaultChecked();
        mAdapter = new AddClothingAdapter(activity, list, R.layout.activity_add_clothing_list_item);
        mAdapter.setOnItemClickListener(mOnflowItemListener);
        mRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 5));
        mRecycler.setAdapter(mAdapter);

        if (!isSingle) {

            mSearchlist = new ArrayList<>();
            hAdapter = new RemoveClothingAdapter(activity, hlist);
            hAdapter.setOnItemClickListener(mRemoveflowItemListener);
            hRecycler.setAdapter(hAdapter);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            hRecycler.setLayoutManager(linearLayoutManager);


        } else {
            addSearchLayout.setVisibility(View.VISIBLE);
        }
    }

    private void defaultChecked() {
        if (!CheckUtils.isEmpty(mDesclist)) {


            for (int i = 0; i < list.size(); i++) {
                AddClothingItem mitem = list.get(i);
                mitem.setCheck(false);
                String strId = mitem.getName() + "";
                for (int j = 0; j < mDesclist.size(); j++) {
                    if (strId.equals(mDesclist.get(j).getName())) {
                        mitem.setPosition(i);
                        mitem.setCheck(true);
                        hlist.add(mitem);
                        strings.add(mitem);

                    }
                }

            }

            if (!CheckUtils.isEmpty(hlist))

                hRecycler.setVisibility(View.VISIBLE);
        }

    }


    private OnItemClickListener mSearchItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            AddClothingItem mAddClothingItem = (AddClothingItem) o;
            String searchId = mAddClothingItem.getName();
            for (int j = 0; j < list.size(); j++) {
                AddClothingItem itemlist = list.get(j);
                if (searchId.equals(itemlist.getName())) {
                    refreshData(j, itemlist, false);
                }
            }
            mSearchPopWindow.dissmiss();
        }
    };


    private MyOnItemClickListener mOnflowItemListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object mObject, int position) {
            //  pos = position;
            AddClothingItem item = (AddClothingItem) mObject;
            refreshData(position, item, false);

        }


    };

    private void refreshData(int position, AddClothingItem item, boolean repetition) {
        if (isSingle) {    /*单选模式*/
            if (!repetition && item.isCheck()) {
                return;
            }


            if (!item.isCheck()) {
                {       /*单选模式勾选*/
                    item.setCheck(true);
                    for (int i = 0; i < list.size(); i++) {
                        if (i != position) {
                            AddClothingItem listeItem = list.get(i);
                            listeItem.setUnitpice("");
                            listeItem.setCheck(false);
                            listeItem.setCount("");
                            listeItem.setUnitText("");

                        }
                    }
                }
            }
        } else { /*多选模式*/

            if (!repetition) {
                item.setCheck(!item.isCheck());
            } else {
                item.setCheck(true);
            }
            if (item.isCheck()) {

                if (!hlist.contains(item)) {
                    item.setPosition(position);
                    hlist.add(item);
                } else {
                    int hlistpos = hlist.indexOf(item);
                    if (hlistpos != -1) {
                        hlist.get(hlistpos).setCount(item.getCount());
                    }
                }


                if (!isSingle && hlist.size() > 0) {
                    hRecycler.setVisibility(View.VISIBLE);
                }
                if (!strings.contains(item)) {
                    strings.add(item);
                } else {
                    int strpos = strings.indexOf(item);
                    if (strpos != -1) {
                        strings.get(strpos).setCount(item.getCount());
                    }
                }
            } else {
                if (hlist.contains(item))
                    hlist.remove(item);
                if (hlist.size() <= 0) {
                    hRecycler.setVisibility(View.GONE);
                }
                if (strings.contains(item)) {
                    strings.remove(item);
                }
            }
        }


        if (!isSingle)
            hAdapter.notifyDataSetChanged();
        mAdapter.notifyDataSetChanged();
    }


    OnItemClickListener mRemoveflowItemListener = new MyOnItemClickListener() {

        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object mObject, int position) {
            super.onItemClick(viewGroup, view, mObject, position);
            AddClothingItem tabeltag = list.get(hlist.get(position).getPosition());

            tabeltag.setCheck(false);
            if (strings.contains(hlist.get(position))) {
                strings.remove(hlist.get(position));
            }
            hlist.remove(position);

            if (hlist.size() <= 0) {
                hRecycler.setVisibility(View.GONE);
            }
            hAdapter.notifyDataSetChanged();
            mAdapter.notifyDataSetChanged();

        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.search_btn, R.id.add_btn, R.id.close_btn, R.id.sure_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.close_btn:
                dismiss();
                break;
            case R.id.sure_btn:
                mJSONArray = new JSONArray();
                mSelectDesclist = new ArrayList<>();
                mStringBuffer = new StringBuffer();
                for (int i = 0; i < list.size(); i++) {
                    AddClothingItem mitem = list.get(i);
                    if (mitem.isCheck()) {
                        addDesc(mJSONArray, mitem);

                    }

                }

                if (mJSONArray.length() > 0) {
                    if (null != mOnClothingListener) {
                        String selectName = mStringBuffer.deleteCharAt(mStringBuffer.length() - 1).toString();
                        mOnClothingListener.onItemSelect(mSelectDesclist, mJSONArray.toString(), selectName, typeEnter);
                        dismiss();
                    }
                } else {
                    dismiss();
                }


                break;
            case R.id.search_btn:
                String searchContext = getText(searchEdit);
                mSearchlist.clear();
                if (searchContext.isEmpty()) return;
                for (AddClothingItem mitem : list) {
                    if (mitem.getName().contains(searchContext)) {
                        mSearchlist.add(mitem);
                    }
                }
                hideKeyboard();
                showPopListView();

                break;
            case R.id.add_btn:

                String addtag = getText(addEdit);
                if (addtag.isEmpty()) {
                    return;
                }

                AddClothingItem mDataBean = new AddClothingItem();
                mDataBean.setName(addtag);
                list.add(0, mDataBean);
                addEdit.setText("");
                mAdapter.notifyDataSetChanged();
                refreshData(0, mDataBean, false);
                break;
        }
    }

    private void addDesc(JSONArray mJSONArray, AddClothingItem s) {
        try {

            JSONObject mJSONObject = new JSONObject();
            mJSONObject.put("id", s.getId());
            mJSONObject.put("name", s.getName());
            StringBean mStringBean = new StringBean(s.getId(), s.getName());
            mStringBuffer.append(s.getName() + "/");
            mSelectDesclist.add(mStringBean);

            mJSONArray.put(mJSONObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void showPopListView() {
        View contentView = LayoutInflater.from(activity).inflate(R.layout.pop_window_search_stockin, null);
        this.searchrecyclerView = (RecyclerView) contentView.findViewById(R.id.search_recyclerView);
        searchrecyclerView.setBackgroundResource(R.drawable.shape_recheck_pop_search);
        mStockinAdapter = new AddClothingAdapter(activity, mSearchlist, R.layout.activity_addclothing_search_list_item);
        searchrecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        mStockinAdapter.setIsSearchEnter(true);
        mStockinAdapter.setOnItemClickListener(mSearchItemClickListener);
        searchrecyclerView.setAdapter(mStockinAdapter);
        mStockinAdapter.setDatas(mSearchlist);


        //创建并显示popWindow
        mSearchPopWindow = new CustomPopWindow.PopupWindowBuilder(activity)
                .setView(contentView)
                .size(searchLayout.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(searchLayout);
    }
}
